import cv2
import os

# 1. 打开摄像头
cap = cv2.VideoCapture(0)
if not cap.isOpened():
    print("无法打开摄像头")
    exit()

# 2. 加载人脸识别模型
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# 3. 创建保存目录
save_dir = "angry_faces"
os.makedirs(save_dir, exist_ok=True)
count = 0  # 用于编号

print("按空格键保存人脸图像，按 ESC 键退出")

while True:
    ret, frame = cap.read()
    if not ret:
        print("无法读取摄像头画面")
        break

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # 4. 检测人脸
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)

    # 5. 显示画面，画出人脸框
    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

    cv2.imshow('Press SPACE to Capture, ESC to Exit', frame)

    key = cv2.waitKey(1)
    if key == 27:  # ESC 退出
        break
    elif key == 32:  # 空格键保存图像
        if len(faces) > 0:
            (x, y, w, h) = faces[0]  # 只保存第一个人脸
            face_img = gray[y:y+h, x:x+w]
            resized = cv2.resize(face_img, (48, 48))

            import uuid

            filename = f"{uuid.uuid4().hex}.png"
            filepath = os.path.join(save_dir, filename)

            cv2.imwrite(filepath, resized)
            print(f"已保存：{filepath}")
            count += 100
        else:
            print("未检测到人脸，未保存。")

cap.release()
cv2.destroyAllWindows()
